import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

//导入
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const routes = [{
  path: '/',
  name: 'Home',
  component: Home,
  meta: {
    auth: true,
    roles:['admin']
  },
  children: [{
    path: '',
    name: 'Home',
    meta: {
      auth: true,
      roles:['admin']
    },
    component: () =>
      import('../views/Homepage.vue'),
  },
  {
    path: 'allOrder',
    name: 'AllOrder',
    meta: {
      auth: true,
      roles:['admin']
    },
    component: () =>
      import('../views/AllOrder.vue'),
  },
  {
    path: 'peopleManagement',
    name: 'PeopleManagement',
    meta: {
      auth: true,
      roles:['admin']
    },
    component: () =>
      import('../views/peopleManagement.vue'),
  },
  {
    path: 'notfond',
    name: 'Notfond',
    meta: {
      auth: false
    },
    component: () =>
      import('../views/Notfond.vue'),
  }]
},
{
  path: '/login',
  name: 'Login',
  component: () =>
    import('../views/Login.vue')
}]


const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})


// 路由拦截（是否已经登录）
router.beforeEach((to, from, next) => {
  // 获取 token
  let token = sessionStorage.getItem('token')

  if (to.meta.auth) { // 该路由需要登录才能访问
    if (token) { // 已经登陆
      next() // 想干嘛干嘛去
      if (to.meta.roles.indexOf(sessionStorage.getItem('username')) > -1) {
        next()
      } else {
        next('/notfond')
      }
    } else {
      next({
        path: '/login',
        query: {
          redirect: to.fullPath // 跳转之前，将原本想访问的路径保存在 query
        }
      })
    }
  } else {
    next() // 该去哪就去哪
  }
})

router.afterEach(() => {
  NProgress.done()
})

export default router